#![allow(non_snake_case)]
use std::collections::HashMap;

use leptos::prelude::*;
use shq_common::prelude::Permission;
use crate::utils::{del_role, del_user, save_role_menus, save_role_users, save_user_menus, save_user_roles, RoleComponent, RoleMenuComponent, RoleUserComponent, UserComponent, UserMenuComponent, UserRoleComponent};

#[component]
pub fn Perm( #[prop(into)] conf_name: Oco<'static, str>) -> impl IntoView {
    let conf_name = StoredValue::new(conf_name.to_string());
    // 创建状态来存储选中的角色ID
    let role_id = RwSignal::new(None::<u32>);
    let user_id = RwSignal::new(None::<u32>);
    
    // 创建状态来存储选中的菜单ID和用户ID
    let selected_role_menu_ids = RwSignal::new(Vec::<String>::new());
    let selected_role_user_ids = RwSignal::new(Vec::<String>::new());
    let selected_user_role_ids = RwSignal::new(Vec::<String>::new());
    let selected_user_menu_ids = RwSignal::new(Vec::<String>::new());
    // 创建加载状态和错误提示状态
    let is_loading = RwSignal::new(false);
    let error_message = RwSignal::new(None::<String>);
    let success_message = RwSignal::new(None::<String>);
    
    // 控制确认对话框的显示
    let show_role_save_confirm = RwSignal::new(false);
    let show_role_delete_confirm = RwSignal::new(false);
    
    // 控制确认对话框的显示
    let show_user_save_confirm = RwSignal::new(false);
    let show_user_delete_confirm = RwSignal::new(false);
    // 保存操作
    let save_role_action = Action::new(move |_| {
        let role_id_val = role_id.get();
        let menu_ids = selected_role_menu_ids.get();
        let user_ids = selected_role_user_ids.get();
        
        async move {
            is_loading.set(true);
            error_message.set(None);
            success_message.set(None);
            
            let role_id_val = match role_id_val {
                Some(id) => id,
                None => {
                    error_message.set(Some("请先选择角色".to_string()));
                    is_loading.set(false);
                    return;
                }
            };
            
            let parsed_permissions = parse_menu_ids(&menu_ids);
            
            let user_ids_result: Result<Vec<u32>, _> = user_ids.iter()
                .map(|id| id.parse::<u32>())
                .collect();
                
            let user_ids = match user_ids_result {
                Ok(ids) => ids,
                Err(e) => {
                    error_message.set(Some(format!("解析用户ID失败: {}", e)));
                    is_loading.set(false);
                    return;
                }
            };
            if parsed_permissions.len() != 0 {
                match save_role_menus(role_id_val, parsed_permissions).await {
                    Ok(_) => {
                        success_message.set(Some("保存菜单权限成功".to_string()));
                        set_timeout(move || {
                            success_message.set(None);
                        }, std::time::Duration::from_millis(3000));
                    }
                    Err(e) => {
                        error_message.set(Some(format!("保存角色菜单失败: {}", e)));
                        set_timeout(move || {
                            success_message.set(None);
                        }, std::time::Duration::from_millis(3000));
                    }
                }
            }
            
            if user_ids.len() != 0 {
            // 保存角色用户
                match save_role_users(role_id_val, user_ids).await {
                    Ok(_) => {
                        success_message.set(Some("保存角色用户成功".to_string()));
                        set_timeout(move || {
                            success_message.set(None);
                        }, std::time::Duration::from_millis(3000));
                    }
                    Err(e) => {
                        error_message.set(Some(format!("保存角色用户失败: {}", e)));
                        set_timeout(move || {
                            success_message.set(None);
                        }, std::time::Duration::from_millis(3000));
                    }
                }
            }
            
            is_loading.set(false);
        }
    });
    // 保存操作
    let save_user_action = Action::new(move |_| {
        let user_id_val = user_id.get();
        let menu_ids = selected_user_menu_ids.get();
        let role_ids = selected_user_role_ids.get();
        
        async move {
            is_loading.set(true);
            error_message.set(None);
            success_message.set(None);
            
            let user_id_val = match user_id_val {
                Some(id) => id,
                None => {
                    error_message.set(Some("请先选择用户".to_string()));
                    is_loading.set(false);
                    return;
                }
            };
            
            let parsed_permissions = parse_menu_ids(&menu_ids);
            
            let role_ids_result: Result<Vec<u32>, _> = role_ids.iter()
                .map(|id| id.parse::<u32>())
                .collect();
                
            let role_ids = match role_ids_result {
                Ok(ids) => ids,
                Err(e) => {
                    error_message.set(Some(format!("解析用户ID失败: {}", e)));
                    is_loading.set(false);
                    return;
                }
            };
            if parsed_permissions.len() != 0 {
                match save_user_menus(user_id_val, parsed_permissions).await {
                    Ok(_) => {
                        success_message.set(Some("保存菜单权限成功".to_string()));
                        set_timeout(move || {
                            success_message.set(None);
                        }, std::time::Duration::from_millis(3000));
                    }
                    Err(e) => {
                        error_message.set(Some(format!("保存角色菜单失败: {}", e)));
                        set_timeout(move || {
                            success_message.set(None);
                        }, std::time::Duration::from_millis(3000));
                    }
                }
            }
            if role_ids.len() != 0 {
                // 保存角色用户
                match save_user_roles(user_id_val, role_ids).await {
                    Ok(_) => {
                        success_message.set(Some("保存角色用户成功".to_string()));
                        set_timeout(move || {
                            success_message.set(None);
                        }, std::time::Duration::from_millis(3000));
                    }
                    Err(e) => {
                        error_message.set(Some(format!("保存角色用户失败: {}", e)));
                        set_timeout(move || {
                            success_message.set(None);
                        }, std::time::Duration::from_millis(3000));
                    }
                }
            }
            is_loading.set(false);
        }
    });
    // 删除操作
    let del_role = Action::new(move |_| {
        let role_id_val = role_id.get();
        
        async move {
            is_loading.set(true);
            error_message.set(None);
            success_message.set(None);
            
            let role_id_val = match role_id_val {
                Some(id) => id,
                None => {
                    error_message.set(Some("请先选择角色".to_string()));
                    is_loading.set(false);
                    return;
                }
            };
            
            match del_role(role_id_val).await {
                Ok(_) => {
                    success_message.set(Some("删除成功".to_string()));
                    role_id.set(None);
                    selected_role_menu_ids.set(Vec::new());
                    selected_role_user_ids.set(Vec::new());
                    set_timeout(move || {
                        success_message.set(None);
                    }, std::time::Duration::from_millis(3000));
                }
                Err(e) => {
                    error_message.set(Some(format!("删除失败: {}", e)));
                    set_timeout(move || {
                        success_message.set(None);
                    }, std::time::Duration::from_millis(3000));
                }
            }
            
            is_loading.set(false);
        }
    });
    let del_user = Action::new(move |_| {
        let user_id_val = user_id.get();
        
        async move {
            is_loading.set(true);
            error_message.set(None);
            success_message.set(None);
            
            let user_id_val = match user_id_val {
                Some(id) => id,
                None => {
                    error_message.set(Some("请先选择用户".to_string()));
                    is_loading.set(false);
                    return;
                }
            };
            
            match del_user(user_id_val).await {
                Ok(_) => {
                    success_message.set(Some("删除成功".to_string()));
                    user_id.set(None);
                    selected_user_menu_ids.set(Vec::new());
                    selected_user_role_ids.set(Vec::new());
                    set_timeout(move || {
                        success_message.set(None);
                    }, std::time::Duration::from_millis(3000));
                }
                Err(e) => {
                    error_message.set(Some(format!("删除失败: {}", e)));
                    set_timeout(move || {
                        success_message.set(None);
                    }, std::time::Duration::from_millis(3000));
                }
            }
            
            is_loading.set(false);
        }
    });
    view! {
        <div class="flex flex-col h-screen p-0">
            // 消息通知区域（响应式显示）
            {move || error_message.get().map(|msg| 
                view! { 
                    <div class="fixed top-4 right-4 z-50 bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded shadow-lg">
                        <p>{msg}</p>
                    </div>
                }
            )}
            
            {move || success_message.get().map(|msg| 
                view! { 
                    <div class="fixed top-4 right-4 z-50 bg-green-100 border-l-4 border-green-500 text-green-700 p-4 rounded shadow-lg">
                        <p>{msg}</p>
                    </div>
                }
            )}
            <div class="flex flex-1 gap-4 min-h-1 p-4 pb-2 max-h-[85vh]"> 
                {view! {
                    <>
                        {if conf_name.get_value() == "role" {
                            view! {
                                <RoleComponent sel_role_id={role_id}  />
                                <RoleMenuComponent sel_role_id={role_id.read_only()} selected_menu_ids={selected_role_menu_ids} />
                                <RoleUserComponent sel_role_id={role_id.read_only()} selected_user_ids={selected_role_user_ids} />
                            }.into_any()
                        } else if conf_name.get_value() == "user" {
                            view! {
                                <UserComponent sel_user_id={user_id} />
                                <UserMenuComponent sel_user_id={user_id.read_only()} selected_menu_ids={selected_user_menu_ids} />
                                <UserRoleComponent sel_user_id={user_id.read_only()} selected_role_ids={selected_user_role_ids} />
                            }.into_any()
                        } else {
                            view! { <div class="text-red-500">"未知的配置名称"</div> }.into_any()
                        }}
                    </>
                }}
            </div>
            <div class="sticky bottom-0 bg-white border-t p-4 flex justify-end gap-4">
            <button 
                class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-medium py-2 px-6 rounded shadow-sm disabled:opacity-50"
                disabled=move || is_loading.get() 
                on:click=move |ev| {
                    ev.prevent_default();
                    if conf_name.get_value() == "role" {
                        show_role_delete_confirm.set(true);
                    } else if conf_name.get_value() == "user" {
                        show_user_delete_confirm.set(true);
                    }
                }
            >
                "清除"
            </button>
            <button 
                class="bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-6 rounded shadow-sm disabled:opacity-50"
                disabled=move || is_loading.get()
                on:click=move |ev| {
                    ev.prevent_default();
                    if conf_name.get_value() == "role" {
                        show_role_save_confirm.set(true);
                    } else if conf_name.get_value() == "user" {
                        show_user_save_confirm.set(true);
                    }
                }
            >
                "保存" 
            </button>
        </div>
            
            {move || show_role_save_confirm.get().then(|| view! {
                <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div class="bg-white rounded-lg p-6 max-w-md w-full">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">"确认保存"</h3>
                        <p class="text-gray-700 mb-6">"你确定要保存当前角色的权限配置吗？"</p>
                        <div class="flex justify-end space-x-4">
                            <button
                                class="px-4 py-2 bg-gray-200 text-gray-800 rounded hover:bg-gray-300 transition-colors"
                                on:click=move |_| show_role_save_confirm.set(false)
                            >
                                "取消"
                            </button>
                            <button
                                class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
                                on:click=move |_| {
                                    show_role_save_confirm.set(false);
                                    save_role_action.dispatch(());
                                }
                            >
                                "确认保存"
                            </button>
                        </div>
                    </div>
                </div>
            })}
            
            {move || show_role_delete_confirm.get().then(|| view! {
                <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div class="bg-white rounded-lg p-6 max-w-md w-full">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">"确认删除"</h3>
                        <p class="text-gray-700 mb-6">"你确定要删除当前选中的角色的权限吗？此操作不可撤销。"</p>
                        <div class="flex justify-end space-x-4">
                            <button
                                class="px-4 py-2 bg-gray-200 text-gray-800 rounded hover:bg-gray-300 transition-colors"
                                on:click=move |_| show_role_delete_confirm.set(false)
                            >
                                "取消"
                            </button>
                            <button
                                class="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700 transition-colors"
                                on:click=move |_| {
                                    show_role_delete_confirm.set(false);
                                    del_role.dispatch(());
                                }
                            >
                                "确认清除"
                            </button>
                        </div>
                    </div>
                </div>
            })}
            {move || show_user_save_confirm.get().then(|| view! {
                <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div class="bg-white rounded-lg p-6 max-w-md w-full">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">"确认保存"</h3>
                        <p class="text-gray-700 mb-6">"你确定要保存当前用户的权限配置吗？"</p>
                        <div class="flex justify-end space-x-4">
                            <button
                                class="px-4 py-2 bg-gray-200 text-gray-800 rounded hover:bg-gray-300 transition-colors"
                                on:click=move |_| show_user_save_confirm.set(false)
                            >
                                "取消"
                            </button>
                            <button
                                class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
                                on:click=move |_| {
                                    show_user_save_confirm.set(false);
                                    save_user_action.dispatch(());
                                }
                            >
                                "确认保存"
                            </button>
                        </div>
                    </div>
                </div>
            })}
            
            {move || show_user_delete_confirm.get().then(|| view! {
                <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div class="bg-white rounded-lg p-6 max-w-md w-full">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">"确认删除"</h3>
                        <p class="text-gray-700 mb-6">"你确定要删除当前选中的用户的权限吗？此操作不可撤销。"</p>
                        <div class="flex justify-end space-x-4">
                            <button
                                class="px-4 py-2 bg-gray-200 text-gray-800 rounded hover:bg-gray-300 transition-colors"
                                on:click=move |_| show_user_delete_confirm.set(false)
                            >
                                "取消"
                            </button>
                            <button
                                class="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700 transition-colors"
                                on:click=move |_| {
                                    show_user_delete_confirm.set(false);
                                    del_user.dispatch(());
                                }
                            >
                                "确认清除"
                            </button>
                        </div>
                    </div>
                </div>
            })}
        </div>
    }
}

fn parse_menu_ids(menu_ids: &[String]) -> Vec<(u32, Permission)> {
    let mut temp_permissions: HashMap<u32, Permission> = HashMap::new();
    
    for menu_id_str in menu_ids {
        let parts: Vec<&str> = menu_id_str.split('_').collect();
        if parts.len() != 3 {
            continue;
        }
        
        let menu_id = match parts[0].parse::<u32>() {
            Ok(id) => id,
            Err(_) => continue,
        };
        
        let per_type = parts[1];
        let value = parts[2];
        
        let permission = temp_permissions.entry(menu_id)
            .or_insert_with(|| Permission {
                auth_types: Vec::new(),
                row_ranges: Vec::new(),
                column_ranges: Vec::new(),
            });
        
        match per_type {
            "auth" => if let Ok(auth_type) = value.parse::<u8>() {
                permission.auth_types.push(auth_type.into());
            },
            "row" => if let Ok(row_range) = value.parse::<u8>() {
                permission.row_ranges.push(row_range.into());
            } else {
                permission.row_ranges = vec![];
            },
            "col" => if let Ok(column_range) = value.parse::<u8>() {
                permission.column_ranges.push(column_range.into());
            } else {
                permission.column_ranges = vec![];
            },
            _ => log::warn!("Unknown permission type: {}", per_type),
        }
    }
    
    temp_permissions.into_iter().collect()
}